package com.winai.launcher.override;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;

import com.winai.launcher.interfaces.CountTimerListener;

/**
 * 作者：康少
 * 时间：2019/11/28 0028
 * 说明：倒计时类
 */
public class AlarmCountTimer extends CountDownTimer {
    @SuppressLint("StaticFieldLeak")
    private static AlarmCountTimer mInstance;
    private static CountTimerListener listener;

    private static AlarmCountTimer getInstance(int seconds) {
        if (mInstance == null) {
            synchronized (AlarmCountTimer.class) {
                mInstance = new AlarmCountTimer(seconds * 1000, 1000);
            }
        }
        return mInstance;
    }

    /**
     * 说明：开始计时器
     */
    public static void start(int minutes, CountTimerListener mAlarmCountTimerListener) {
        if (mInstance != null) {
            mInstance.cancel();
        }
        mInstance = null;
        if (mAlarmCountTimerListener != null) {
            listener = mAlarmCountTimerListener;
        }
        mInstance = getInstance(minutes);
        if (mInstance != null) {
            mInstance.start();
        }
    }

    /**
     * 说明：释放定时器
     */
    public static void release() {
        if (mInstance != null) {
            mInstance.cancel();
        }
        mInstance = null;
    }

    /**
     * 参数 millisInFuture       倒计时总时间（如60S，120s等）
     * 参数 countDownInterval    渐变时间（每次倒计1s）
     */
    public AlarmCountTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    // 计时完毕时触发
    @Override
    public void onFinish() {
        if (listener != null) {
            listener.onFinish();
        }
    }

    // 计时过程显示
    @Override
    public void onTick(long millisUntilFinished) {
        if (listener != null) {
            listener.onTick(millisUntilFinished);
        }
    }
}
